//
//  ModuleManager.m
//  Autobots
//
//  Created by 张志恒 on 16/11/8.
//  Copyright © 2016年 Autohome. All rights reserved.
//

#import "RTModuleManager.h"

@interface RTModuleManager ()

@property (nonatomic, strong) NSMutableArray<RTModule *> *modules;

@end

@implementation RTModuleManager

+ (instancetype)sharedInstance
{
    static RTModuleManager *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (NSMutableArray<RTModule *> *)modules
{
    if (!_modules) {
        _modules = [NSMutableArray array];
    }
    return _modules;
}

- (void)addModule:(RTModule *) module
{
    if (![self.modules containsObject:module]) {
        [self.modules addObject:module];
    }
}

- (void)loadModulesWithPlistFile:(NSString *)plistFile
{
    NSArray *dicts = [NSArray arrayWithContentsOfFile:plistFile];
    for (NSDictionary *dic in dicts) {
        RTModule *module = [[RTModule alloc] initWithDictionary:dic];
        [self addModule:module];
    }
}

- (NSArray<RTModule *> *)allModules
{
    return self.modules;
}

#pragma mark - UIApplicationDelegate's methods

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    for (RTModule *module in self.modules) {
        if ([module.moduleClass respondsToSelector:_cmd]) {
            [module.moduleClass application:application didFinishLaunchingWithOptions:launchOptions];
        }
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    for (RTModule *module in self.modules) {
        if ([module.moduleClass respondsToSelector:_cmd]) {
            [module.moduleClass applicationWillResignActive:application];
        }
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    for (RTModule *module in self.modules) {
        if ([module.moduleClass respondsToSelector:_cmd]) {
            [module.moduleClass applicationDidEnterBackground:application];
        }
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    for (RTModule *module in self.modules) {
        if ([module.moduleClass respondsToSelector:_cmd]) {
            [module.moduleClass applicationWillEnterForeground:application];
        }
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    for (RTModule *module in self.modules) {
        if ([module.moduleClass respondsToSelector:_cmd]) {
            [module.moduleClass applicationDidBecomeActive:application];
        }
    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    for (RTModule *module in self.modules) {
        if ([module.moduleClass respondsToSelector:_cmd]) {
            [module.moduleClass applicationWillTerminate:application];
        }
    }
}

@end
